from mashup.models import Article, Source, Photo
from django.http import HttpResponse,HttpResponseRedirect,Http404
from django.shortcuts import render_to_response
from django.core import serializers

MAX_SHOW = 5

def index(request):
    return render_to_response('mashup/index.html')

def get_latest(model, src, max_show=MAX_SHOW):
    return model.objects.order_by('-pub_date').filter(
                        source__name__contains=src)[:max_show]

def response_json(model, src, max_show=MAX_SHOW):
    qs = get_latest(model, src, max_show)     
    data = serializers.serialize("json", qs )
    return HttpResponse(data)

def my_import(name):
    """helper to return module from name 'package.module'"""

    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod

def ajax(request, src):
    """dispatch url to proper view"""   

    m = my_import(ajax.__module__)   
    view = 'ajax_' + src
    if not hasattr(m, view):
        raise Http404
    return getattr(m, view)(request)

def ajax_digg(request):
    return response_json(Article, 'digg.com' )

def ajax_delicious(request):
    return response_json(Article, 'del.icio.us') 

def ajax_boingboing(request):
    return response_json(Article, 'boingboing.net', 3) 

def ajax_flickr(request):
    return response_json(Photo, 'flickr.com') 

